<template>
    <el-dialog :close-on-click-modal="false" :title="titleMap" v-model="visible" :width="1200" destroy-on-close @closed="$emit('closed')">
        <div class="tipsbox">使用指导:1、选择时间和课程类型，2、选择教练，查看其可用时间(绿色)</div>
        <el-container>
            <el-container class="is-vertical">
                <div class="panel-search-box">
                    <div class="panel-search">
                        <el-button @click="changeDateFun(1)">上一周</el-button>
                        <el-button @click="changeDateFun(2)">上一天</el-button>
                        <el-date-picker
                            clearable
                            v-model="search.workTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            :default-value="search.workTime"
                            :disabled-date="disabledDate"
                            @change="selectTimeFun"
                            placeholder="选择上课日期"
                        >
                        </el-date-picker>
                        <div style="color: red;">{{ week }}</div>
                        <el-button @click="changeDateFun(3)">下一天</el-button>
                        <el-button @click="changeDateFun(4)">下一周</el-button>
                        <el-select v-model="search.courseType" placeholder="课程类型" clearable>
                            <el-option label="30分钟课" :value="1"></el-option>
                            <el-option label="60分钟课" :value="2"></el-option>
                            <el-option label="体验课" :value="4"></el-option>
                        </el-select>
                        <el-select
                            v-model="search.name"
                            filterable
                            remote
                            clearable
                            placeholder="请输入教练名称搜索"
                            :remote-method="searchTeacherHander"
                            :loadings="teacherLoading">
                            <el-option
                                v-for="item in teacherList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.name"
                                :disabled="item.disabled">
                            </el-option>
                        </el-select>
                        <el-button type="primary" icon="el-icon-search" @click="upsearch">查询</el-button>
                        <div>颜色说明：</div>
                        <el-button style="background-color: rgb(249, 167, 167);
    color: white;">休息</el-button>
                        <el-button style="background-color: rgb(255, 202, 2);
    color: white;">已预约</el-button>
                        <el-button style="background-color: rgb(128, 197, 49);
    color: white;">空闲(可点击预约)</el-button>
                    </div>
                    <div class="panel-search" v-if="selectTimeList.length > 0">
                        <div class="selected-time" v-for="(item, index) in selectTimeList" :key="index">
                            {{ item.teacher.name + '：' + item.startTime }}
                            <span class="selected-time-close" @click="timeDeleteHandle(index)">
                                <i class="el-icon-close"></i>
                            </span>
                        </div>
                        <el-button type="danger" icon="el-icon-check" @click="table_save">开始预约</el-button>
                    </div>
                </div>
                <el-main class="nopadding">
                <scTable ref="table" :apiObj="apiObj" remoteSort @dataChange="dataChange" :height="400">
                    <el-table-column label="序号" prop="index" width="70" align="left"></el-table-column>
                    <el-table-column label="教练" prop="name" width="120" align="center">
                    </el-table-column>
                    <el-table-column label="预约次数" prop="appointmentNumber" width="120" align="center">
                    </el-table-column>
                    <el-table-column label="时间段" prop="timeSchedule" align="center">
                        <template #default="scope">
                            <template v-if="!scope.row.timeSchedule || scope.row.isAllWork == 1">
                                <div class="all-day-work" @click="table_time(scope.row)">全天工作</div>
                            </template>
                            <template v-if="scope.row.isAllWork == 2">
                                <div class="all-day-rest">全天休息</div>
                            </template>
                            <template v-if="scope.row.isAllWork == 0 && scope.row.timeSchedule && scope.row.timeSchedule.length > 0">
                                <div class="time-box">
                                    <template v-for="item in scope.row.timeSchedule">
                                        <template v-if="item.type == 1">
                                            <div class="time timeFree" @click="table_time(scope.row, item)">{{ item.startTime + '~' + item.endTime}}</div>
                                        </template>
                                        <template v-else>
                                            <div class="time" :class="{timeArrange: item.type == 2, timeAppointment: item.type == 3}">{{ item.startTime + '~' + item.endTime}}</div>
                                        </template>
                                    </template>
                                </div>
                            </template>
                        </template>
                    </el-table-column>
                </scTable>
                </el-main>
            </el-container>
        </el-container>
    </el-dialog>

    <timeSelectDialog v-if="dialog.timeSelect" ref="timeSelectDialog" @success="timeSuccessHandle"></timeSelectDialog>

    <saveDialog v-if="dialog.save" ref="saveDialog" @success="successHandle"></saveDialog>

</template>

<script>
import timeSelectDialog from './timeSelect.vue'
import saveDialog from './formSave.vue'
export default {
    components: {
        timeSelectDialog,
        saveDialog
    },
    data() {
        return {
            titleMap: '创建预约(教练优先)',
            dialog: {
                timeSelect: false,
                save: false
            },
            loading: false,
            teacherLoading: false,
            visible: false,
            userLoading: false,
            isSaveing: false,
            search: {
                startDate: '',
                courseType: '',
                name: ''
            },
            teacherId: '',
            userList: [],
            userCourses: [],
            appointmentNumbers: 0, //可预约次数
            teacherList: [],
            selectTimeList: [],
            week: '',
            apiObj: {}
        }
    },
    created() {
        this.search.workTime = this.getDateFun()
        this.week = this.getWeekFun(this.search.workTime)
    },
    mounted() {
        this.searchTeacherHander('')
    },
    methods: {
        //显示
        open() {
            this.visible = true;
            return this
        },
        // 搜索
        upsearch() {
            if (this.search.workTime == '') {
                this.$notify.error('请选择上课日期')
                return
            }
            if (this.search.courseType == '') {
                this.$notify.error('请选择课程类型')
                return
            }
            this.apiObj = this.$API.teacher.timeList
            this.$refs.table.upData(this.search)
        },
        dataChange(res, tableData) {
			let total = res.data.total
            let perPage = res.data.perPage
            let page = (this.$refs.table && this.$refs.table.currentPage) || 1
            tableData.forEach((item, index) => {
				item.index = page * perPage + index - perPage + 1
            })
        },
        table_time(row, time) {
            let param = {
                teacher: {
                    id: row.id,
                    name: row.name
                },
                isAllWork: row.isAllWork,
                courseType: this.search.courseType
            }
            if (time) {
                param.startTime = time.startTime
                param.endTime = time.endTime
            }else{
                param.startTime = '00:00'
                param.endTime = '23:00'
            }

            this.dialog.timeSelect = true
            this.$nextTick(() => {
                this.$refs.timeSelectDialog.open('3.请选择开始时间', param)
            })
        },
        table_save() {
            let params = {
                courseType: this.search.courseType,
                teachers: this.selectTimeList
            }
            this.dialog.save = true
            this.$nextTick(() => {
                this.$refs.saveDialog.open('4.填写交付方式、学员姓名和课程名称').setData(params)
            })
        },
        getDateFun(time) {
            let now = time ? new Date(time) : new Date();
            let year = now.getFullYear(); //得到年份
            let month = now.getMonth(); //得到月份
            let date = now.getDate(); //得到日期
           
            month = month + 1;
            month = month.toString().padStart(2, "0");
            date = date.toString().padStart(2, "0");
            let defaultDate = `${year}-${month}-${date}`;//
            return defaultDate;
        },
        getWeekFun(time) {
            //根据time获取星期几
            let week = new Date(time).getDay();
            let weekMap = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
            return weekMap[week];
        },
        changeDateFun(type) {
            //type 1: 上一周  2：上一天  3：下一天  4：下一周
            let time = new Date(this.search.workTime).getTime();
            let oneDay = 24 * 60 * 60 * 1000;
            if (type == 1) {
                //上一周
                time = time - 7 * oneDay;
            } else if (type == 2) {
                //上一天
                time = time - oneDay;
            } else if (type == 3) {
                //下一天
                time = time + oneDay;
            } else if (type == 4) {
                //下一周
                time = time + 7 * oneDay;
            }

            this.search.workTime = this.getDateFun(time);
            this.week = this.getWeekFun(this.search.workTime);

            if (this.search.courseType && this.search.workTime) {
                this.upsearch()
            }
        },
        //禁用今天之前的日期
        disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
        },
        selectTimeFun(row) {
            this.week = this.getWeekFun(this.search.workTime);
        },
        timeSuccessHandle(row) {
            let _date = new Date(this.search.workTime)
            let year = _date.getFullYear(); 
            let month = _date.getMonth();
            let day = _date.getDate();

            month = month + 1;
            month = month.toString().padStart(2, "0");
            day = day.toString().padStart(2, "0");

            let _startTime = `${year}-${month}-${day} ${row.startTime}`

            for(let key in this.selectTimeList) {
                if (this.selectTimeList[key].startTime == _startTime) {
                    this.$notify.error('时间重复')
                    return false
                }
                let _time1 = new Date(this.selectTimeList[key].startTime).getTime();
                let _time2 = new Date(_startTime).getTime();
                 
                if (Math.abs(_time1 - _time2) < 90 * 60 * 1000) {
                    this.$notify.error('间隔时间太短，您已选择了：' + this.selectTimeList[key].startTime)
                    return false
                }
            }
            
            this.selectTimeList.push({
                teacher: row.teacher,
                startTime: `${year}-${month}-${day} ${row.startTime}`,
            })
            this.dialog.timeSelect = false
        },
        searchTeacherHander(query) {
            this.teacherLoading = true;
            this.$API.teacher.listByName.get({name:query}).then((res) => {
                this.teacherList = res.data
            }).finally(() => {
                this.teacherLoading = false
            });
        },
        timeDeleteHandle(index) {
            this.selectTimeList.splice(index, 1)
        },
        successHandle() {
            this.visible = false
            this.$emit('success')
        }
    }
}
</script>

<style scoped>

.tipsbox {
    left: 17px;
    position: relative;
    bottom: 13px
}

.selected-time {
    background-color: #80c531;
    color: #fff;
    margin-right: 5px;
    padding: 7px 5px;
}

.selected-time-close {
    color: red; 
    margin: 0px 5px; 
    cursor: pointer;
}

.all-day-work {
    background-color: #80c531;
    cursor: pointer;
    color: #fff;
}

.all-day-rest {
    background-color: rgb(249, 167, 167);
    color: #fff;
}

.time-box {
    display: flex; 
    align-items: center; 
    flex-wrap: wrap;
}

.time {
    margin-right: 5px;
    padding: 5px;
}

.timeFree {
    background-color: #80c531;
    color: #fff;
    cursor: pointer;
}

.timeAppointment {
    background-color: rgb(255, 202, 2);
    color: #fff;
}

.timeArrange{
    background-color: #f9a7a7;
    color: #fff;
}

</style>